package itsec1.cardmanagement;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import javax.net.ssl.SSLHandshakeException;

public class CustomerManagementRequestHandler implements Runnable {
	@SuppressWarnings("unused")
	private CardManagement cm;
	private Socket socket;
		
	public CustomerManagementRequestHandler(CardManagement cm, Socket socket) {
		this.cm = cm;
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {			
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            
            String request= in.readLine();
            
            String[] split= request.split(";");
            String result=null;
            
            //mockup methods
            if(split.length == 2)
            {
	            if(split[0].equals("getCardLimit"))
	            {
	            	result= "100";
	            }else if(split[0].equals("getCardNumbers")){
	            	result= "100000000000;200000000000";
	            }else if(split[0].equals("isValid")){
	            	result= "true";
	            }else if(split[0].equals("setCardLimit")){
	            	result= "true";
	            }else if(split[0].equals("deleteCard")){
	            	result= "true";
	            }else if(split[0].equals("insertCard")){
	            	result= "true";
	            }else{
	            	System.out.println("unkown/unauthorized request for "+split[0]);
	            	result= "Request denied";
	            }
            }           
            
            if(result == null)
            	result= "Request denied";
            
            out.write(result);
        	out.newLine();
        	out.flush();            
        }catch(SSLHandshakeException e){
        	System.out.println("Card Management Request rejected due to unkown certificate being used by "+socket.getInetAddress()+":"+socket.getPort());
        }catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        } // catch
        try {
            socket.close();
        } catch ( Exception e ) {}
	}
	
	
}
